'use strict';

const Service = require('egg').Service;

class table extends Service {
  // 查表
  async query(id, name, page, pageSize) {
    const { app } = this;
    const result = app.response.listResult();
    const where = {};
    if (id) {
      where.id = id;
    }
    if (name) {
      where.name = name;
    }
    result.page = page;
    result.pageSize = pageSize;
    result.data = await app.mysql.select('table', {
      where,
      ...app.paging(page, pageSize),
    });
    const count = await app.mysql.count('table');
    result.total = count;
    return result;
  }

  // 创建
  async create(name, power_role, index) {
    const { app } = this;
    const data = {
      name,
      create_time: Date.now(),
    };
    if (app.validate(power_role).int()) {
      data.power_role = power_role;
    }
    if (app.validate(index).int()) {
      data.index = index;
    }
    const result = await app.mysql.insert('table', data);
    if (result.affectedRows) {
      return result.insertId;
    }
  }

  // 更新表
  async update(id, name, power_role, index) {
    const { app } = this;
    const data = {
      modify_time: Date.now(),
    };
    if (app.validate(name).hasString()) {
      data.name = name;
    }
    if (app.validate(power_role).int()) {
      data.power_role = power_role;
    }
    if (app.validate(index).int()) {
      data.index = index;
    }

    const result = await app.mysql.update('table', data, {
      where: { id },
    });
    if (result.changedRows) {
      return true;
    }
  }

  // 删表
  async delete(ids) {
    const { app } = this;
    const all = ids.map(i => +i).map(id => {
      return app.mysql.delete('table', { id });
    });
    await Promise.all(all);
    return true;
  }

  // 导入表
  async import(name, fields, rows) {
    const { service } = this;

    const tableId = await service.table.create(name);

    await service.field.addmost(tableId, fields);

    const rowList = await service.row.add(tableId, null, rows);

    return rowList;
  }
}

module.exports = table;
